package org.come.test;


import java.lang.management.ManagementFactory;
import java.util.List;

public class AntiAgent {

    // 主入口：请在 main() 或系统初始化时尽早调用
    public static void init() {
        blockAttachClassLoading();       // 拦截 VirtualMachine 类
        detectJavaAgent();               // 检查是否使用 -javaagent 参数启动
        detectDebugger();                // 检查是否被调试器附加M
    }

    // AttachBlocker：通过自定义类加载器拦截 attach 相关类
    private static void blockAttachClassLoading() {
        ClassLoader blockingLoader = new ClassLoader(Thread.currentThread().getContextClassLoader()) {
            @Override
            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                if (name.startsWith("com.sun.tools.attach.") || name.contains("VirtualMachine")) {
                    throw new ClassNotFoundException("Blocked attach class: " + name);
                }
                return super.loadClass(name, resolve);
            }
        };
        Thread.currentThread().setContextClassLoader(blockingLoader);
        System.out.println("[AntiAgent] Attach class loading blocked.");
    }

    // AgentDetector：检测 -javaagent 参数是否存在
    private static void detectJavaAgent() {
        List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
        for (String arg : args) {
            if (arg.startsWith("-javaagent")) {
                System.err.println("[AntiAgent] Detected javaagent argument: " + arg);
                panic("Java Agent detected");
            }
        }
    }

    // DebugDetector：检测调试器附加（如通过 JDWP）
    private static void detectDebugger() {
        List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
        for (String arg : args) {
            if (arg.contains("jdwp") || arg.contains("debug")) {
                System.err.println("[AntiAgent] Debugger detected: " + arg);
                panic("Debugger detected");
            }
        }
    }

    // 统一退出机制（可自定义为抛异常、记录日志等）
    private static void panic(String message) {
        System.err.println("[AntiAgent] PANIC: " + message);
        System.exit(101);  // 自定义退出码
    }
}
